package cn.tedu.captcha_demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;


import cn.tedu.captcha_demo.model.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Miyako
 * @Date: 2024-08-29-16:37
 * @Description:使用redis存储验证码后，前后端分离获取
 */
@Slf4j
@RestController
@RequestMapping("/v1")
@CrossOrigin//请求跨域
public class CaptchaController {
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("cap")
    public JsonResult getCaptcha() {
        //创建糊涂工具类对象，来生成验证码图像
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100,50,4,100);
        //获取验证码内容
        String code = lineCaptcha.getCode();
        log.debug(code);
        //将验证码存储到Redis中
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("code",(Serializable)code,10, TimeUnit.SECONDS);
        log.debug("储存成功");


        //获取用Base64编码的图片JSON字符串
        String imageBase64Data = lineCaptcha.getImageBase64Data();
        log.debug(imageBase64Data);


       return new JsonResult(2000,"success",imageBase64Data);

//        //将验证码保存到session中
//        session.setAttribute("code",code);

//        //获取前端输出流对象
//        ServletOutputStream stream = response.getOutputStream();
//        //输出流输出到前端页面
//        lineCaptcha.write(stream);
//
//        stream.close();
    }
}
